package model;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.lang.reflect.Parameter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-01-13
 * Time: 下午 20:40
 */
public class DBUtil {

    private volatile static DataSource source = null;

    private DBUtil() {

    }

    public static DataSource getDataSource() {

        if(source == null) {
            synchronized (DBUtil.class) {
                if(source == null) {
                    source = new MysqlDataSource();
                    ((MysqlDataSource)source).setURL("jdbc:mysql://127.0.0.1:3306/blog_system_java104?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");
                    ((MysqlDataSource)source).setUser("root");
                    ((MysqlDataSource)source).setPassword("123456");
                }
            }
        }
        return source;
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {

        //如果资源对象不存在就去释放空间,肯定会导致空指针异常,空指针异常以后就没办法在去执行其他代码.导致该释放的没有释放不需要释放的确异常了
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}
